package com.yls.autoapply.server;

import com.yls.autoapply.exception.SshRunException;
import com.yls.autoapply.exception.SshTimeoutException;
import com.yls.autoapply.model.SshResponse;
import com.yls.autoapply.util.CmdUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class MasterServer extends ServerAbs {

    public SshResponse cat(String file, String grep) throws IOException, SshTimeoutException, SshRunException {
        String cmd = String.format(CmdUtil.cat, file, grep);
        return super.runCmd(cmd);
    }

    public SshResponse sed(String file, String source, String dest) throws IOException, SshTimeoutException, SshRunException {
        String cmd = String.format(CmdUtil.sed, source, dest, file);
        return super.runCmd(cmd);
    }
    public SshResponse apply(String file) throws IOException, SshTimeoutException, SshRunException {
        String cmd = String.format(CmdUtil.apply, file);
        return super.runCmd(cmd);
    }

    public SshResponse version(String namespace) throws IOException, SshTimeoutException, SshRunException {
        String cmd = String.format(CmdUtil.deploy, namespace);
        String result = super.runCmd(cmd).getStdOutput();
        cmd = String.format(CmdUtil.daemon, namespace);
        SshResponse response = super.runCmd(cmd);
        response.setStdOutput(response.getStdOutput() + result);
        return response;
    }

    @Override
    public void close() {
        try {
            if (getFs() != null) {
                getFs().close();
            }

            if (getSftpClient() != null) {
                getSftpClient().close();
            }

            if (getSession() != null) {
                getSession().close();
            }
        } catch (Exception e) {
            log.error("" + e);
        }
        getClient().stop();
    }
}
